package config

import (
	"os"
	"path/filepath"
	"sync"
	"time"

	"github.com/BurntSushi/toml"
	"github.com/sirupsen/logrus"
)

var once sync.Once

func init() {
	Conf.Api.Bind = "0.0.0.0:8100"

	Conf.Redis.RedisAddress = "127.0.0.1:6379"
	Conf.Redis.RedisPassword = ""
	Conf.Redis.Db = 3

	Conf.Server.WriteWait = 10 * time.Second
	Conf.Server.PongWait = 11 * time.Second
	Conf.Server.PingPeriod = 9 * time.Second
	Conf.Server.BroadcastSize = 64
	Conf.Server.MaxMessageSize = 4096
	Conf.Server.ReadBufferSize = 1024
	Conf.Server.WriteBufferSize = 1024

	Conf.Tcp.ServerId = "server-1"
	Conf.Tcp.Bind = "0.0.0.0:8200"
	Conf.Tcp.SendBuf = 4096
	Conf.Tcp.ReceiveBuf = 4096
	Conf.Tcp.KeepAlive = false
	Conf.Tcp.Reader = 32
	Conf.Tcp.ReadBuf = 1024
	Conf.Tcp.ReadBufSize = 8192
	Conf.Tcp.Writer = 32
	Conf.Tcp.WriteBuf = 1024
	Conf.Tcp.WriteBufSize = 8192

	Conf.WS.Bind = "0.0.0.0:8300"

	Conf.Connect.CpuNum = 4

	once.Do(func() {
		confPath, _ := filepath.Abs(filepath.Dir(os.Args[0]) + "/config/config.toml")
		if _, err := toml.DecodeFile(confPath, &Conf); err != nil {
			logrus.Error("DecodeFile Error! ", err)
			return
		}
	})
}

const (
	RedisValidTime = 86400 * time.Second
	QueueName      = "litetalk_channel"
	RedisPrefix    = "litetalk_"
	RedisOnline    = RedisPrefix + "online_"
)

var (
	Conf Config
)

type Config struct {
	Api     ApiConfig   `toml:"api-base"`
	Redis   CommonRedis `toml:"redis-base"`
	Tcp     ConnectTCP  `toml:"connect-tcp"`
	WS      ConnectWS   `toml:"connect-ws"`
	Connect ConnectConfig
	Server  ServerConfig
}

type CommonRedis struct {
	RedisAddress  string
	RedisPassword string
	Db            int
}

type ConnectConfig struct {
	CpuNum int
}

type ConnectTCP struct {
	ServerId     string `toml:"serverId"`
	Bind         string `toml:"bind"`
	SendBuf      int    `toml:"sendbuf"`
	ReceiveBuf   int    `toml:"receviebuf"`
	Reader       int    `toml:"reader"`
	ReadBuf      int    `toml:"readbuf"`
	ReadBufSize  int    `toml:"readbufsize"`
	Writer       int    `toml:"writer"`
	WriteBuf     int    `toml:"writebuf"`
	WriteBufSize int    `toml:"writebufsize"`
	KeepAlive    bool
}

type ConnectWS struct {
	Bind string `toml:"bind"`
}

type ServerConfig struct {
	WriteWait       time.Duration
	PongWait        time.Duration
	PingPeriod      time.Duration
	MaxMessageSize  int64
	ReadBufferSize  int
	WriteBufferSize int
	BroadcastSize   int
}

type ApiConfig struct {
	Bind      string          `toml:"bind"`
	WhiteList map[string]bool `toml:"white"`
}
